$(function () {
    query();
    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    $.ajax({
        url: "/ret/partyparamget/getUnitTypeTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            $.fn.zTree.init($("#unitTypeTree"), unittypesetting, data);
        }
    });
    $("#unitType").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#unitTypeContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });

    $.ajax({
        url: "/ret/partyparamget/getUnitSuboTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            var topNode = [{
                sortName: "TOP全部",
                isParent: "false",
                sortId: ""
            }];
            var newTreeNodes = topNode.concat(data);
            $.fn.zTree.init($("#unitAffiliationTree"), unitAffiliationsetting, data);
            $.fn.zTree.init($("#unitAffiliationQueryTree"), unitAffiliationQuerysetting, newTreeNodes);
        }
    });
    $("#unitAffiliation").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#unitAffiliationContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });

    $("#unitAffiliationQuery").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#unitAffiliationQueryContent").css({
            "width": $(this).outerWidth() + "px",
            "left": $(this).position().left + "px"
        }).slideDown(200);
    });

    $("#serviceIndustryQuery").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#serviceIndustryQueryContent").css({
            "width": $(this).outerWidth() + "px",
            "left": $(this).position().left + "px"
        }).slideDown(200);
    });

    $.ajax({
        url: "/ret/partyparamget/getUnitIndustryTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            $.fn.zTree.init($("#industryTree"), industrysetting, data);
        }
    });
    $("#industry").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#industryContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });

    $.ajax({
        url: "/ret/partyparamget/getUnitServiceTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            var topNode = [{
                sortName: "TOP全部",
                isParent: "false",
                sortId: ""
            }];
            var newTreeNodes = topNode.concat(data);
            $.fn.zTree.init($("#serviceIndustryTree"), serviceIndustrysetting, data);
            $.fn.zTree.init($("#serviceIndustryQueryTree"), serviceIndustryQuerysetting, topNode);
        }
    });
    $("#serviceIndustry").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#serviceIndustryContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });

    $("body").unbind("click").click(function () {
        $(".menuContent").hide();
    });

    $(".menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });

    $("#createbut").unbind("click").click(function () {
        addPartyUnitBase();
    })
})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/partyorgget/getUnitBaseInfoList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',// 工具列
        striped: true,// 隔行换色
        cache: false,// 禁用缓存
        pagination: true,// 启动分页
        sidePagination: 'server',// 分页方式
        pageNumber: 1,// 初始化table时显示的页码
        pageSize: 10,// 每页条目
        showFooter: false,// 是否显示列脚
        showPaginationSwitch: true,// 是否显示 数据条数选择框
        sortable: true,// 排序
        search: true,// 启用搜索
        sortOrder: "asc",
        showColumns: true,// 是否显示 内容列下拉框
        showRefresh: true,// 显示刷新按钮
        idField: 'unitId',// key值栏位
        clickToSelect: true,// 点击选中checkbox
        pageList: [10, 20, 30, 50],// 可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',// 标题 可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'unitName',
            title: '单位全称',
            width: '150px',
            formatter:function (value,row,index)
            {
                return "<a href=\"javascript:void(0);details('" + row.unitId + "')\" style='cursor: pointer'>"+value+"</a>";
            }
        }, {
            field: 'shortName',
            width: '100px',
            title: '单位简称'
        }, {
            field: 'subordinateUnit',
            width: '150px',
            title: '隶属单位名称',
            formatter: function (value, row, index) {
                if (value != "0") {
                    return getUnitName(value)
                } else {
                    return "无";
                }
            }
        }, {
            field: '',
            width: '100px',
            title: '单位类型',
            formatter: function (value, row, index) {
                var returnStr = [];
                if (row.unitType1 == "1") {
                    returnStr.push("独立法人单位");
                }
                if (row.unitType2 == "1") {
                    returnStr.push("建立党员服务机构");
                }
                if (row.unitType3 == "1") {
                    returnStr.push("建立党员志愿者队伍");
                }
                return returnStr.join(",");
            }
        }, {
            field: 'linkTel',
            width: '100px',
            title: '单位联系电话'
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '120px',
            formatter: function (value, row, index) {
                return createOptBtn(row.unitId);
            }
        }],
        onClickCell: function (field, value, row, $element) {
            // alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, // 总页数,前面的key必须为"total"
                    rows: res.list.list
                    // 行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        partyStatus: $("#partyStatusQuery").val(),
        unitAffiliation: $("#unitAffiliationQuery").attr("data-value"),
        serviceIndustry: $("#serviceIndustryQuery").attr("data-value")
    };
    return temp;
};

function createOptBtn(unitId) {
    var html = "<a href=\"javascript:void(0);edit('" + unitId + "')\" class=\"btn btn-primary btn-xs\">编辑</a>&nbsp;&nbsp;" +
        "<a href=\"javascript:void(0);deleteUnit('" + unitId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    return html;
}

function deleteUnit(unitId) {
    if (confirm("确定删除当前活动吗？")) {
        $.ajax({
            url: "/set/partyorgset/deletePartyUnitBase",
            type: "post",
            dataType: "json",
            data: {
                unitId: unitId
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}

function edit(unitId) {
    $("#unitlistdiv").hide();
    $("#unitdiv").show();
    $("#joinUser").attr("data-value", "");
    $(".js-back-btn").unbind("click").click(function () {
        goback();
    })
    $.ajax({
        url: "/ret/partyorgget/getPartyUnitBaseById",
        type: "post",
        dataType: "json",
        data: {
            unitId: unitId
        },
        success: function (data) {
            if (data.status == "200") {
                var recordInfo = data.list;
                for (var id in recordInfo) {
                    if (id == "unitType") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $.ajax({
                            url: "/ret/partyparamget/getPartyUnitTypeById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: recordInfo[id]
                            },
                            success: function (res) {
                                if (res.status == "200") {
                                    $("#" + id).val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else if (res.status == "500") {
                                    console.log(res.msg);
                                }
                            }
                        })
                    } else if (id == "unitAffiliation") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $.ajax({
                            url: "/ret/partyparamget/getPartyUnitSuboById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: recordInfo[id]
                            },
                            success: function (res) {
                                if (res.status == "200") {
                                    $("#" + id).val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else if (res.status == "500") {
                                    console.log(res.msg);
                                }
                            }
                        })
                    } else if (id == "industry") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $.ajax({
                            url: "/ret/partyparamget/getPartyUnitIndustryById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: recordInfo[id]
                            },
                            success: function (res) {
                                if (res.status == "200") {
                                    $("#" + id).val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else if (res.status == "500") {
                                    console.log(res.msg);
                                }
                            }
                        })
                    } else if (id == "serviceIndustry") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $.ajax({
                            url: "/ret/partyparamget/getPartyUnitServiceById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: recordInfo[id]
                            },
                            success: function (res) {
                                if (res.status == "200") {
                                    $("#" + id).val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else if (res.status == "500") {
                                    console.log(res.msg);
                                }
                            }
                        })
                    } else if (id == "unitType1") {
                        if (recordInfo[id] == "1") {
                            $("#unitType1").prop("checked", "checked");
                        }
                    } else if (id == "unitType2") {
                        if (recordInfo[id] == "1") {
                            $("#unitType2").prop("checked", "checked");
                        }
                    } else if (id == "unitType3") {
                        if (recordInfo[id] == "1") {
                            $("#unitType3").prop("checked", "checked");
                        }
                    } else if (id == "subordinateUnit") {
                        var select2 = $("#subordinateUnit").select2({
                            ajax: {
                                url: "/ret/partyorgget/getSelect2UnitBaseList",
                                dataType: 'json',
                                type: "POST",
                                delay: 250,
                                data: function (params) {
                                    return {search: params.term};
                                },
                                processResults: function (datas) {
                                    var datares = {results: []};
                                    var datalist = datas.list;
                                    datares.results.push({id: "0", text: "无"});
                                    for (var i = 0; i < datalist.length; i++) {
                                        var record = datalist[i];
                                        var name = record.unitName != '' ? record.unitName : record.shortName;
                                        var option = {
                                            "id": record.unitId,
                                            "text": name
                                        };
                                        datares.results.push(option);
                                    }
                                    return datares;
                                },
                                cache: true
                            },
                            language: 'zh-CN',
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            minimumInputLength: 2,
                            placeholder: "请输入单位名称",
                        })
                        $("#subordinateUnit").append(new Option(getUnitName(recordInfo[id]), recordInfo[id], true, true));//第一个参数时id,第二个参数是text
                        $("#subordinateUnit").trigger("change");
                    } else {
                        $("#" + id).val(recordInfo[id]);
                    }
                }
                $(".js-update-save").unbind("click").click(function () {
                    updateUnitBase(unitId);
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function details(unitId) {
    window.open("/app/core/partyorg/partyworkdetails?unitId=" + unitId);
}

function getUnitName(unitId) {
    var retStr = "";
    $.ajax({
        url: "/ret/partyorgget/getPartyUnitBaseById",
        type: "post",
        dataType: "json",
        async: false,
        data: {
            unitId: unitId
        },
        success: function (data) {
            if (data.status == "200") {
                if (data.list) {
                    retStr = data.list.unitName;
                } else {
                    retStr = "";
                }
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
    return retStr;
}

function updateUnitBase(unitId) {
    if ($("#unitName").val()== "") {
        layer.msg("单位名称不能为空！");
        return;
    }
    $.ajax({
        url: "/set/partyorgset/updatePartyUnitBase",
        type: "post",
        dataType: "json",
        data: {
            unitId: unitId,
            unitName: $("#unitName").val(),
            shortName: $("#shortName").val(),
            unitType: $("#unitType").attr("data-value"),
            partyStatus: $("#partyStatus").val(),
            creditCode: $("#creditCode").val(),
            unitAffiliation: $("#unitAffiliation").attr("data-value"),
            industry: $("#industry").attr("data-value"),
            serviceIndustry: $("#serviceIndustry").attr("data-value"),
            address: $("#address").val(),
            legalPerson: $("#legalPerson").val(),
            linkTel: $("#linkTel").val(),
            unitType1: getCheckBoxValue("unitType1"),
            unitType2: getCheckBoxValue("unitType2"),
            unitType3: getCheckBoxValue("unitType3"),
            subordinateUnit: $("#subordinateUnit").val()
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function goback() {
    $("#unitdiv").hide();
    $("#unitlistdiv").show();
}

var unittypesetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getUnitTypeTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("unitTypeTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#unitType");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};

var unitAffiliationsetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getUnitSuboTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("unitAffiliationTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#unitAffiliation");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};
var unitAffiliationQuerysetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getUnitSuboTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("unitAffiliationQueryTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#unitAffiliationQuery");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};
var industrysetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getUnitIndustryTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("industryTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#industry");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};
var serviceIndustrysetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getUnitServiceTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("serviceIndustryTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#serviceIndustry");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};

var serviceIndustryQuerysetting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyparamget/getUnitServiceTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("serviceIndustryQueryTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#serviceIndustryQuery");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};
